<template>
    <div :ref="id" class="chart"></div>
</template>

<script>
import echarts from 'echarts'
import themeGhost from './themes/themeGhost.json'
export default {
  name: 'chart',
  props: {
    id: {
      type: String,
      require: true
    },
    option: {
      type: Object,
      default: () => {}
    },
    mapData: {
      type: Object,
      default: () => {}
    },
    dependence: {
      type: String
    }
  },
  data () {
    return {
      chart: null
    }
  },
  watch: {
    option: {
      handler (val, oldVal) {
        this.initChart()
      },
      deep: true
    }
  },
  beforeCreate () {
    const that = this
    that.echarts = echarts
    that.echarts.registerTheme('theme', themeGhost)
  },
  mounted () {
    const that = this
    // 如果依赖是字符云，则引入字符云，无法通过传字符串直接动态引入
    /*if (that.dependence === 'echarts-wordcloud') {
      require('echarts-wordcloud')
    }*/
    /*// 如果依赖是水球图，则引入水球图，无法通过传字符串直接动态引入
    if (that.dependence === 'echarts-liquidfill') {
      require('echarts-liquidfill')
    }*/
    for (let i in that.mapData) {
      that.echarts.registerMap(i, that.mapData[i])
    }
    that.chart = that.echarts.init(that.$refs[that.id], 'theme')
    that.chart.on('click', function (params) {
      that.$emit('chartClick', {
        data: params
      })
    })
    window.addEventListener('resize', function () {
      that.chart.resize()
    })
    that.chart.showLoading({
      text: '数据加载中...',
      color: '#c23531',
      textColor: '#fff',
      maskColor: 'rgba(0, 0, 0, 0.8)',
      zlevel: 0
    })
    that.initChart()
  },
  methods: {
    initChart () {
      const that = this
      that.chart.setOption(that.option, {
        notMerge: true
      })
      that.chart.hideLoading()
      that.$emit('chartInit', that.chart)
    }
  }
}
</script>

<style lang="scss" scoped>
    .chart{
        width: 100%;
        height: 100%;
    }
</style>
